<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="obj">
              {{
                obj.row.timeOfEntry | formatDate
              }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('point-user-delete')" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="page.total" :current-page="page.page" :page-size="page.size" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>

    <!-- 放置新增组件 -->
    <add-employee :show-dialog.sync="showDialog" />

    <!-- 放置角色分配组件 -->
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import { formatDate } from '@/filters'
import assignRole from './components/assign-role'
export default {
  components: {
    AddEmployee,
    assignRole
  },
  data() {
    return {
      loading: false, // 这个是没有加载完之前转圈
      list: [], // 接收获取到的后台数据
      page: { // 分页的数据
        page: 1, // 当前页码
        size: 6,
        total: 0 // 总数
      },
      showDialog: false, // 打开弹层
      showRoleDialog: false, // 显示分配角色组件
      userId: null// 存储当前的用户id
    }
  },
  created() {
    // 初始化数据
    this.getEmployeeList()
  },
  methods: {
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 接收后台的数据
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      console.log(rows)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    // 状态的格式化
    formatEmployment(row, column, cellValue, index) {
      const list = EmployeeEnum.hireType // 获取枚举数组
      const obj = list.find(item => item.id === cellValue)
      return obj ? obj.value : '未知' // 应该返回 返回的值就会被渲染到表格上
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 导出excel表格
    exportExcel() {
      // 加载表头
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取表格的数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.convertData(headers, rows)
        excel.export_json_to_excel({
          // 这个是设置excel的表头
          header: Object.keys(headers),
          // 这个是设置表格内容
          data,
          // 这个是设置表的名字
          filename: '员工表',
          // 宽度
          autoWidth: true
        })
      })
    },
    // 转换数据的方法
    convertData(headers, result) {
      return result.map(item => {
        return Object.keys(headers).map(key => {
          // 判断是否是时间
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            item[headers[key]] = formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const en = (EmployeeEnum.hireType.find(result => result.id === item[headers[key]]))
            item[headers[key]] = en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 编辑角色
    async  editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
